package com.lagou.service.impl;

import com.lagou.dao.UserMapper;
import com.lagou.pojo.Result;
import com.lagou.pojo.User;
import com.lagou.service.AuthCodeService;
import com.lagou.service.TokenService;
import com.lagou.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.Date;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenService tokenService;

    @Reference
    private AuthCodeService authCodeService;

    @Override
    public User getByEmail(String email) {
        User user = new User();
        user.setEmail(email);
        Example<User> example = Example.of(user);
        Optional<User> optional = userMapper.findOne(example);
        if(!optional.isPresent()){
            return null;
        }
        return optional.get();
    }

    @Override
    public User save(User user) {
        return userMapper.save(user);
    }

    @Override
    public Result register(String email, String password, String code) {
        User user = getByEmail(email);
        if(user != null){
            return new Result(1);
        }

        //校验验证码
        if(authCodeService.validate(email, code) != 0){
            return new Result(2);
        }

        user = new User();
        user.setEmail(email);
        user.setPassword(password);
        user.setCreatetime(new Date());
        save(user);

        // ⽣成签发token令牌
        return new Result(0, tokenService.createToken(email));
    }
}
